package questionmanager;

import gui.GUIMain;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map.Entry;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import rmi.Answer;
import rmi.Question;
import stuff.FixedSizeDocument;

public class GUIQuestionEdit extends JDialog{
	private static final long serialVersionUID = 1L;
	public static final String DEFAULT_STRING = "Chưa đính kèm ảnh";
	
	private Question question;
	private JTextArea taQuestion;
	
	private JLabel lbDisplayImage;
	private JButton btChooseImage;
	private JButton btClearImage;
	
	private JPanel answerPanel;
	private ArrayList<AnswerDisplay> tfAnswers;
	private JButton btNewAnswer;
	private JButton btOK;
	private JButton btCancel;
	private ButtonGroup group;
	private GridBagConstraints c;
	private int typeCount;
	private Integer[] typeInt;
	
	public GUIQuestionEdit(JFrame parent, int qID) {
		super(parent, "Chỉnh sửa câu hỏi", true);
		setLayout(new BorderLayout());
		tfAnswers = new ArrayList<>();
		
		JPanel topPanel = new JPanel(new BorderLayout());
		topPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
		JLabel label = new JLabel("Câu hỏi : ");
		topPanel.add(label,BorderLayout.NORTH);
		this.taQuestion = new JTextArea();
		this.taQuestion.setRows(3);
		this.taQuestion.setDocument(new FixedSizeDocument(10000));
		JScrollPane questionPane = new JScrollPane(taQuestion);
		topPanel.add(questionPane,BorderLayout.CENTER);
		
		JPanel bottom = new JPanel(new BorderLayout());
		lbDisplayImage = new JLabel(DEFAULT_STRING);
		btChooseImage = new JButton(new ButtonChooseImageAction());
		btChooseImage.setText("Chọn...");
		btClearImage = new JButton(new ButtonClearImageAction());
		btClearImage.setText("Xoá");
		bottom.add(lbDisplayImage,BorderLayout.CENTER);
		JPanel imageButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		imageButtons.add(btChooseImage);
		imageButtons.add(btClearImage);
		bottom.add(imageButtons,BorderLayout.EAST);
		
		String[] typeString;
		try {
			ArrayList<String> rstemp = new ArrayList<>();
			ArrayList<Integer> rxtemp = new ArrayList<>();
			LinkedHashMap<Integer,String> temp = GUIMain.getDb().getAllQuestionTypes();
			typeString = new String[temp.size()];
			typeInt = new Integer[temp.size()];
			
			for(Entry<Integer, String> count : temp.entrySet()){
				rxtemp.add(count.getKey());
				rstemp.add(count.getValue());
			}
			rxtemp.toArray(typeInt);
			rstemp.toArray(typeString);
			
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}
		
		JLabel typeLabel = new JLabel("Loại câu hỏi: ");
		final JComboBox<String> type = new JComboBox<>(typeString); 
		type.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				typeCount = type.getSelectedIndex();
			}
		});
		
		JPanel typePanel = new JPanel(new GridBagLayout());
		GridBagConstraints zxc = new GridBagConstraints();
		zxc.gridx = 0;
		zxc.gridy = 0;
		
		typePanel.add(typeLabel, zxc);
		
		zxc.gridx = 1;
		zxc.fill =GridBagConstraints.BOTH;
		zxc.weightx = 1;
		typePanel.add(type, zxc);
		bottom.add(typePanel,BorderLayout.SOUTH);
		topPanel.add(bottom, BorderLayout.SOUTH);
		
		///////////////////////////////////
		answerPanel = new JPanel();
		JScrollPane pane = new JScrollPane(answerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		pane.setBorder(new EmptyBorder(0, 0, 0, 0));
		answerPanel.setLayout(new GridBagLayout());
		c = new GridBagConstraints();
		c.fill = GridBagConstraints.BOTH;
		c.weightx = 1;
		c.gridx = 0;
		c.gridy = 0;
		group = new ButtonGroup();
		
		try{
			question = GUIMain.getDb().getQuestionsByQuestionID(qID);
			this.taQuestion.setText(question.getQuestion());
			if(question.getQuestionImageLink().equals("")){
				this.lbDisplayImage.setText(DEFAULT_STRING);
			}else{
				this.lbDisplayImage.setText(question.getQuestionImageLink());
			}
			for(int i = 0; i<typeInt.length; i++){
				if(typeInt[i].intValue() == question.getQuestionType()){
					type.setSelectedIndex(i);
					break;
				}
			}
			
			for(Entry<Integer, Answer> count : question.getMapAnswers().entrySet()){
				AnswerDisplay ad;
				ad = new AnswerDisplay(count.getKey().intValue(), false , count.getValue().getAnswerContent(),count.getValue().isShow());
				ad.setGroup(group);
				tfAnswers.add(ad);
				answerPanel.add(tfAnswers.get(tfAnswers.indexOf(ad)),c);
				c.gridy++;
			}
			
			int aid = GUIMain.getDb().GetTrueAnswerByQuestion(qID);
			for(int i = 0; i< tfAnswers.size();i++){
				if(aid == tfAnswers.get(i).getAID()){
					tfAnswers.get(i).setIsTrue(true);
					break;
				}
			}
		}catch (SQLException e) {
			e.printStackTrace();
			return;
		}
		
		JPanel btPanel = new JPanel(new BorderLayout());
		JPanel btLeft = new  JPanel(new FlowLayout(FlowLayout.LEFT));
		btNewAnswer = new JButton(new ButtonNewAction());
		btNewAnswer.setText("Thêm...");
		btLeft.add(btNewAnswer);
		
		JPanel btRight = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		btOK = new JButton(new ButtonOKAction());
		btOK.setText("Sửa");
		btCancel = new JButton(new ButtonCancelAction());
		btCancel.setText("Thoát");
		btRight.add(btOK);
		btRight.add(btCancel);
		btPanel.add(btLeft,BorderLayout.WEST);
		btPanel.add(btRight,BorderLayout.EAST);
		
		add(topPanel,BorderLayout.NORTH);
		add(pane,BorderLayout.CENTER);
		add(btPanel,BorderLayout.SOUTH);
	}
	
	public boolean editQuestion(){
		if(question==null) return false;
		
		if(taQuestion.getText().trim().equals("")){
			JOptionPane.showMessageDialog(this, "Câu hỏi không được để trống!", 
					"Lỗi", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
		boolean selectedTrue = false;
		for(AnswerDisplay count : tfAnswers){
			if(count.getAnswer().trim().equals("")){
				JOptionPane.showMessageDialog(this, "Các câu trả lời không được để trống!", 
						"Lỗi", JOptionPane.ERROR_MESSAGE);
				return false;
			}
			if(count.getIsTrue()){
				selectedTrue = true;
			}
		}
		
		if(!selectedTrue){
			JOptionPane.showMessageDialog(this, "Cần lựa chọn đáp án đúng cho câu hỏi!", 
					"Lỗi", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
		if(updateDB()){
			JOptionPane.showMessageDialog(this, "Cập nhật thành công!", 
					"Thành công", JOptionPane.INFORMATION_MESSAGE);
			return true;
			
		}else{
			return false;
		}
		
	}
	
	private boolean updateDB(){
		for(AnswerDisplay count : tfAnswers){
			if(count.getAID()>=0){
				if(count.getIsTrue()){
					if(!GUIMain.getDb().UpdateAnswer(count.getAID(), count.getAnswer(), question.getQuestionID(), true, true)){
						JOptionPane.showMessageDialog(this, "Cập nhật câu trả lời : \"" + count.getAnswer() + "\" bị lỗi", 
								"Lỗi", JOptionPane.ERROR_MESSAGE);
						}
				}else if(!GUIMain.getDb().UpdateAnswer(count.getAID(), count.getAnswer(), question.getQuestionID(), false, count.isShow())){
						JOptionPane.showMessageDialog(this, "Cập nhật câu trả lời : \"" + count.getAnswer() + "\" bị lỗi", 
								"Lỗi", JOptionPane.ERROR_MESSAGE);
						}
					
				
			}else{
				if(!GUIMain.getDb().InsertAnswer(count.getAnswer(), question.getQuestionID(), count.getIsTrue(),true)){
					JOptionPane.showMessageDialog(this, "Tạo mới câu trả lời : \"" + count.getAnswer() + "\" bị lỗi", 
							"Lỗi", JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		int type = this.typeInt[this.typeCount].intValue();
		String imageLinkInput =lbDisplayImage.getText().trim();
		if(imageLinkInput.equals(DEFAULT_STRING)){
			imageLinkInput = "";
		}
		if(!GUIMain.getDb().UpdateQuestion(question.getQuestionID(), taQuestion.getText().trim(),imageLinkInput, type, question.getPriority())){
			JOptionPane.showMessageDialog(this, "Cập nhật câu hỏi : \"" + taQuestion.getText().trim() + "\" bị lỗi", 
					"Lỗi", JOptionPane.ERROR_MESSAGE);
		}
		return true;
	}
	
	class ButtonNewAction extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			AnswerDisplay ad = new AnswerDisplay(-1, false, "Câu trả lời", true);
			ad.setGroup(group);
			tfAnswers.add(ad);
			answerPanel.add(tfAnswers.get(tfAnswers.indexOf(ad)),c);
			c.gridy++;
			answerPanel.revalidate();
		}
	}
	
	class ButtonOKAction extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if(editQuestion()){
				dispose();
			}
		}
	}
	
	class ButtonCancelAction extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			dispose();
		}
	}
	
	class ButtonClearImageAction extends AbstractAction{
		
		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			lbDisplayImage.setText(DEFAULT_STRING);
		}
	}
	
	class ButtonChooseImageAction extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent e) {
			JFileChooser chooser = new JFileChooser();
			chooser.setCurrentDirectory(new java.io.File("."));
			chooser.setDialogTitle("Chọn ảnh");
			chooser.setAcceptAllFileFilterUsed(false);
			chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			chooser.addChoosableFileFilter(new FileNameExtensionFilter("Tập tin hình ảnh...","jpg", "png", "bmp", "jpeg"));

			if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
				lbDisplayImage.setText(chooser.getSelectedFile().toString());
			}
		}
	}
	
	class AnswerDisplay extends JPanel{
		
		private static final long serialVersionUID = 1L;
		private int id;
		private final JRadioButton isTrue;
		private boolean isShow;
		private final JTextField answer;
		private JButton remove;
		
		public AnswerDisplay(int id, boolean isTrue, String answer, boolean isShow) {
			this.id = id;
			this.isTrue = new JRadioButton();
			this.answer = new JTextField();
			this.answer.setDocument(new FixedSizeDocument(10000));
			this.answer.setText(answer);
			this.remove = new JButton("Xoá");
			this.isShow = isShow;
			
			setLayout(new BorderLayout());
			JPanel left = new JPanel();
			left.setLayout(new BoxLayout(left, BoxLayout.X_AXIS));
			left.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
			left.add(this.isTrue);
			left.add(this.answer);
			JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			right.add(remove);
			
			add(left,BorderLayout.CENTER);
			add(right,BorderLayout.EAST);
			
			this.remove.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					int index;
					for(int i = 0; i < tfAnswers.size();i++){
						if(AnswerDisplay.this.id == tfAnswers.get(i).getAID() 
								&& AnswerDisplay.this.answer.getText().equals(tfAnswers.get(i).getAnswer())){
							index = i;
							if(tfAnswers.get(index).getAID() < 0){
							}else{
								GUIMain.getDb().DeleteAnswer(tfAnswers.get(index).getAID());
							}
							tfAnswers.remove(index);
							answerPanel.remove(index);
							answerPanel.repaint();
							break;
						}
					}
					
				}
			});
			
		}
		
		public void setGroup(ButtonGroup ex){
			ex.add(isTrue);
		}
		
		public boolean getIsTrue(){
			return isTrue.isSelected();
		}
		
		public void setIsTrue(boolean is){
			isTrue.setSelected(is);
		}
		
		public String getAnswer(){
			return this.answer.getText();
		}
		
		public int getAID(){
			return this.id;
		}

		public boolean isShow() {
			return isShow;
		}
		
		public void setIsShow(boolean isShowing){
			isShow = isShowing;
		}
		
	}
	
}
